<?php
declare (strict_types = 1);

namespace app\helper;

/**
 * 一些常用的方法
 */
class CommonHelper
{
    /**
     * site_url标准化处理
     * @param string $site_url
     * @param boolean $encrypt
     * @return string
     */
    public static function site_url_standard(string $site_url, bool $encrypt = false) : string
    {
        $site_url = rtrim($site_url, '/');
        return $encrypt ? md5($site_url) : $site_url;
    }

    /**
     * 获取url的域名信息
     * @param string $url
     * @return string
     */
    public static function get_url(string $url) : string
    {
        $url = parse_url($url);
        if(!$url){
            return '';
        }

        $scheme = isset($url['scheme']) ? $url['scheme'] : 'https';
        $host = $url['host'];
        $port = isset($url['port']) ? $url['port'] : '';

        return $scheme . '://' . $host . $port;
    }

    /**
     * 根据url获取域名特征信息
     * 例：https://www.baidu.com/ -> baidu
     * @param string $url
     * @return string
     */
    public static function get_url_host_key(string $url) : string
    {
        $url = strtolower($url);
        $host = parse_url($url, PHP_URL_HOST);
        
        //查看是几级域名
        $data = explode('.', $host);
        $n = count($data);

        //判断是否是双后缀
        $preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/';
        return ($n > 2) && preg_match($preg,$host) ? $data[$n-3]: $data[$n-2];
    }


    /**
     * 获取随机密码
     * @param integer $len
     * @return string
     */
    public static function get_rand_str(int $len = 32) : string
    {
        $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@#%!_";
        return substr(str_shuffle($characters), 0, $len); 
    }
}